<?php
/*
 * Страница со списком регионов с заказщиками, их контрактами и жалобами
*/

class multitender_action_distributor_list extends multitender_action {

    function run() {
	exit("Извините, данный раздел был удален!");
	

        $official_link = 'http://rnp-gz.fas.gov.ru/';
        $region_id = @ $_GET['region_id'] ? $_GET['region_id'] : NULL;
        $id_distributor = @ $_GET['id_distributor'] ? $_GET['id_distributor'] : NULL;
        $filter = @ $_REQUEST['filter'] ? $_REQUEST['filter'] : NULL;
        $contract_id = @ $_GET['contract_id'] ? $_GET['contract_id'] : NULL;
        $complaint_id = @ $_GET['complaint_id'] ? $_GET['complaint_id'] : NULL;
        $complaints = @ $_GET['complaints'] ? $_GET['complaints'] : NULL;

        $filter = preg_replace('#[^a-zа-яё0-9/_]#iu', ' ', $filter);
        $filter = trim(preg_replace('/\s+/', ' ', $filter));
        $filter = trim($filter);

        $names = explode(' ', $filter);
        $filter = '';
        foreach ($names as $v) {
            if (mb_strlen($v,'UTF-8') >= 3) {
                $filter .= $v . ' ';
            }
        }
        $filter = trim($filter);
        $cm = $this->new_model('distributor_list');

        $link_base = $this->conf['pref']['link_base'];
        $link_act  = "distributor_list";
        $rectopg = 25;
        $page = @ $_GET['page'] ? $_GET['page'] : 1;

        if ($region_id && !$id_distributor && !$contract_id  && !$complaint_id) {
            $region = $cm->get_date_region($region_id);
            $this->conf['page_title'] = 'Поставщики ' . $region['name_rp'] . '. Адреса поставщиков, контракты и жалобы. Статистика выигранных тендеров и доходов от них.';
            $tpl = $this->new_tpl();
            $offset=($page-1) * $rectopg;

            $distributors = $cm->get_distributors_list($region_id, $offset, $rectopg, $filter, $complaints);
            $total = $distributors['total'];
            unset($distributors['total']);

            $ids = array();
            foreach ($distributors as &$distributor) {
                if ($filter) {
                    $names = explode(' ', $filter);
                    foreach ($names as $v) {
                        $distributor["Name"] = ltrim(preg_replace("/^[\.,\?\-_!()]/", '', ltrim($distributor['Name']),1));
                        $distributor["Name"] = preg_replace("/$v/iu", '<font color=#cc0000>\\0</font>', @ $distributor["Name"] ? $distributor["Name"] : "Поставщик");
                        $distributor["INN"] = preg_replace("/$v/iu", '<font color=#cc0000>\\0</font>', @ $distributor["INN"] ? $distributor["INN"] : "-");

                    }
                }
                $ids[] = $distributor['id'];
                $distributor['link'] = substr($link_base,0,-1) . $link_act. "?id_distributor=" . $distributor['id'];
            }
            reset($distributors);
            if ($items = $cm->get_items_by_ids($ids)) {
                foreach ($distributors as &$distributor) {
                    foreach ($items as $item) {
                        if ($item['id_distributor']==$distributor['id']) {
                            $distributor['count_items'] = $item['count'];
                            
                        }
                    }
                }

            }

            $scrol = $this->new_action("scrol");
            $link = "?region_id=".$region_id;
            if ($filter) {
                $fr = "&filter=$filter";
            } else {
                $fr = "";
            }
            if ($complaints) {
                $compl = "&complaints=only";
            } else {
                $compl = "";
            }
            $scrol->link = '/tenders/distributor_list/'.$link.$fr.$compl.$scrol->link;
            $scrol->total = $total;
            $scrol->onpage = $rectopg;
            $tpl->assign('scrol', $scrol->run());
            $tpl->assign('filter', $filter);
            $tpl->assign('total', $total);
            $tpl->assign('link_base', substr($link_base,0,-1));
            $tpl->assign('link_act', $link_act);
            $tpl->assign('region', $region);
            $tpl->assign('distributors', $distributors);
            $tpl->assign('compl', $complaints);

            return $tpl->fetch("distributor_list_reg.tpl");

        } elseif (!$region_id && $id_distributor && !$contract_id  && !$complaint_id) {
            $tpl = $this->new_tpl();
            
            $tpl->caching = true;
            $tpl->cache_lifetime = mt_rand(10, 15) * 60*60;

            $infor = $cm->get_distributor_info_by_id($id_distributor);
            $x = $cm->get_region_of_distributor($infor['region_id']);
            $infor['region_name'] = $x['name'];

            $this->conf['page_title'] = $infor['Name'] . '. Поставщик ' . $x['name_rp'] . '. Адрес, контракты и жалобы. Статистика выигранных тендеров и доходов от них.';

            if (!$tpl->is_cached('distributor_info.tpl', $id_distributor . '-' . $page)) {

                //$infor['region_name'] = $infor['region_name']['name'];
                $offset = ($page-1)*$rectopg;
                $contracts = $cm->get_contracts_of_distributor($id_distributor, $offset, $rectopg);
                $total = $contracts['count'];
                unset ($contracts['count']);
                foreach ($contracts as &$item) {
                    $item['contract_date'] = @ $item['contract_date'] != "1970-01-02" ? date("d.m.Y", strtotime($item['contract_date'])-86400) : '-';
                    $item['contract_end_date'] = @ $item['contract_end_date'] != "1970-01-02" ? date("d.m.Y", strtotime($item['contract_end_date'])-86400) : '-';
                    $item['customer_name'] = ltrim(preg_replace("/^[\.,\?\-_!()]/", '', ltrim($item['customer_name']),1));
                    $item['customer_name'] = @ $item['customer_name']? $item['customer_name'] :'Заказчик';
                    $item['link'] = substr($link_base,0,-1) . $link_act. "?id_distributor=" . $id_distributor . "&contract_id=" . $item['id'];
                    $item['contract_price'] = @ $item['contract_price'] != 0 ? (@ number_format($item['contract_price']/1000, 0, '.', ' ') !=  0 ? number_format($item['contract_price']/1000, 0, '.', ' ') : number_format($item['contract_price']/1000, 3, '.', ' ')) : '-';
                }
                $complaints = $cm->get_complaints_of_distributor($id_distributor);
                $complaints_count = $complaints['count'];
                unset ($complaints['count']);
                reset($complaints);
                $complaintsstring="";//если найдеться ошибка, то переделать!
                
                //foreach ($complaints as &$items) {
                //    $items['Date_of_Auction_Result'] = @ $items['Date_of_Auction_Result'] != "1970-01-02" ? date("d.m.Y", strtotime($items['Date_of_Auction_Result'])) : '-';
                //    $items['Date_of_execution'] = @ $items['Date_of_execution'] != "1970-01-02" ? date("d.m.Y", strtotime($items['Date_of_execution'])) : '-';
                //    $items['link'] = substr($link_base,0,-1) . $link_act. "?id_distributor=" . $id_distributor . "&complaint_id=" . $items['id'];
                //    $items['Sum'] = @ $items['Sum'] != 0 ? (@ number_format($items['Sum']/1000, 0, '.', ' ') != 0 ? number_format($items['Sum']/1000, 0, '.', ' ') : number_format($items['Sum']/1000, 3, '.', ' ')) : '-';
                //}
                $i=0;
                foreach ($complaints as $items) {
                    $complaintsstring .= "<tr  onclick=\"go('" . substr($link_base,0,-1) . $link_act. "?id_distributor=" . $id_distributor . "&complaint_id=" . $items['id'] . "');\">";

                    $complaintsstring .= '<td align="left"><a href="' . substr($link_base,0,-1) . $link_act. "?id_distributor=" . $id_distributor . "&complaint_id=" . $items['id'] . '" title="Подробная информация по жалобе">' . $items['Subject_of_Contract'] . '</a></td>';
                    $complaintsstring .= '<td align="left">'. (@ $items['Date_of_execution'] != "1970-01-02" ? date("d.m.Y", strtotime($items['Date_of_execution']) -86400) : '-') . '</td>';
                    $complaintsstring .= '<td align="left">' . (@ $items['Date_of_execution'] != "1970-01-02" ? date("d.m.Y", strtotime($items['Date_of_execution'])-86400) : '-') . '</td>';
                    $complaintsstring .= '<td align="left">' . (@ $items['Sum'] != 0 ? (@ number_format($items['Sum']/1000, 0, '.', ' ') != 0 ? number_format($items['Sum']/1000, 0, '.', ' ') : number_format($items['Sum']/1000, 3, '.', ' ')) : '-') . '</td></tr>';
                    $i++;
                }

                $scrol = $this->new_action("scrol");
                $link = "?id_distributor=".$id_distributor;
                $scrol->link = '/tenders/distributor_list/'.$link.$scrol->link;
                $scrol->total = $total;
                $scrol->onpage = $rectopg;
                
                
                $tpl->assign('scrol', $scrol->run());
                $tpl->assign('filter', $filter);
                reset($complaints);
                //$tpl->assign("complaints", $complaints);
                $tpl->assign("complaints", $complaintsstring);
                $tpl->assign("backlink", "/tenders/distributor_list?region_id=" . $infor['region_id']);
                $tpl->assign("complaints_count", $complaints_count);
                $tpl->assign("mas", $infor);
                $tpl->assign("contracts", $contracts);
                $tpl->assign("count", $total);
                $mas = $cm->get_graph_info($id_distributor);
                if ($mas != FALSE) {
                    foreach ($mas as $items) {
                        $res[$items['year_gr']] = round($items['dohod']/1000);
                    }
                    $grapher = $this->new_action('grapher');
                    $graph = $grapher->draw_column(array('Сумма за год, тыс. руб.'=>$res),
                            'Статистика доходов организации по годам', '', 700, 300);
                    $tpl->assign('graph', $graph);
                }
            }

            return $tpl->fetch('distributor_info.tpl', $id_distributor . '-' . $page);
        } elseif (!$region_id && $id_distributor && $contract_id && !$complaint_id) {
            $tpl = $this->new_tpl();
            $tpl->caching = true;
            $tpl->cache_lifetime = mt_rand(10, 15) * 60 * 60;
            $distributor_info = $cm->get_distributor_info_by_id($id_distributor);
            $this->conf['page_title'] = $distributor_info['Name'] . '. Контракты поставщика. Выигранные тендеры.';
            if (!$tpl->is_cached('contract_info.tpl', $contract_id)) {
               
                $ar = $cm->get_region_of_distributor($distributor_info['region_id']);
                $distributor_info['region_name'] = $ar['name'];

                

                $contract_info = $cm->get_contract_info($contract_id);
                $goods = $cm->get_goods($contract_info['id_in_source']);
                $total = $goods['count'];
                unset ($goods['count']);

                if ($contract_info['execution_type'] == 108) {
                    $contract_info['execution_type'] = 'Расторгнут';
                } elseif ($contract_info['execution_type'] == 109) {
                    $contract_info['execution_type'] = 'Исполнен';
                } elseif ($contract_info['execution_type'] == 101) {
                    $contract_info['execution_type'] = 'Действующий';
                }
                $contract_info['contract_date'] = @ $contract_info['contract_date'] != "1970-01-02" ? date("d.m.Y", strtotime($contract_info['contract_date']) -86400) : '-';
                $contract_info['contract_end_date'] = @ $contract_info['contract_end_date'] != "1970-01-02" ? date("d.m.Y", strtotime($contract_info['contract_end_date'])-86400) : '-';
                $contract_info['contract_price'] = @ $contract_info['contract_price'] != 0 ? (@ number_format($contract_info['contract_price']/1000, 0, '.', ' ') != 0 ? number_format($contract_info['contract_price']/1000, 0, '.', ' ') : number_format($contract_info['contract_price']/1000, 3, '.', ' ')) : '-';

                foreach ($goods as &$items) {
                    $items['name'] = ltrim(preg_replace("/^[\.,\?\-_!()]/", '', ltrim($items['name']),1));
                    $items['name'] = @ $items['name'] ? $items['name'] : 'Товар';
                    $items['sum'] = @ $items['price']*$items['count'] == 0 ? '-' : (@ number_format($items['price']*$items['count']/1000, 0, '.', ' ') !=0 ? number_format($items['price']*$items['count']/1000, 0, '.', ' ') : number_format($items['price']*$items['count']/1000, 3, '.', ' '));
                    $items['price'] = @ $items['price'] == 0 ? '-' : ( @ number_format($items['price']/1000, 0, '.', ' ') != 0 ? (number_format($items['price']/1000, 0, '.', ' ')) : (number_format($items['price']/1000, 3, '.', ' ')));
                    $items['count'] = @ $items['count'] == 0 ? '-' : $items['count'];
                }
                $tpl->assign("id_dist", $id_distributor);
                $tpl->assign("contract", $contract_info);
                $tpl->assign("distributor", $distributor_info);
                $tpl->assign("goods", $goods);
                $tpl->assign("count", $total);

            }

            return $tpl->fetch('contract_info.tpl', $contract_id);
        } elseif (!$region_id && $id_distributor && !$contract_id && $complaint_id) {
            $tpl = $this->new_tpl();
            $tpl->caching = true;
            $tpl->cache_lifetime = mt_rand(10, 15) * 60 * 60;
            $distributor_info = $cm->get_distributor_info_by_id($id_distributor);
            $this->conf['page_title'] = $distributor_info['Name'] . '. Жалобы на поставщика..';
            
            if (!$tpl->is_cached('complaint_info.tpl', $complaint_id)) {
                
                $ar = $cm->get_region_of_distributor($distributor_info['region_id']);
                $distributor_info['region_name'] = $ar['name'];
                
                $complaint = $cm->get_complaint_info_by_distributor_id($complaint_id);

                $complaint['Date_of_Inclusion'] = @ $complaint['Date_of_Inclusion'] != "1970-01-02" ? date("d.m.Y", strtotime($complaint['Date_of_Inclusion']) -86400) : '-';
                $complaint['Date_of_Auction_Result'] = @ $complaint['Date_of_Auction_Result'] != "1970-01-02" ? date("d.m.Y", strtotime($complaint['Date_of_Auction_Result'])-86400) : '-';
                $complaint['Date_of_execution'] = @ $complaint['Date_of_execution'] != "1970-01-02" ? date("d.m.Y", strtotime($complaint['Date_of_execution'])-86400) : '-';
                
                $complaint['Sum'] = @ $complaint['Sum'] != 0 ? (@ number_format($complaint['Sum']/1000, 0, '.', ' ') != 0 ? number_format($complaint['Sum']/1000, 0, '.', ' ') : number_format($complaint['Sum']/1000, 3, '.', ' ')) : '-';
                $complaint['link'] = $official_link . $complaint['link'];
                
                $tpl->assign("distributor", $distributor_info);
                $tpl->assign("complaint", $complaint);
                $tpl->assign("id_dist", $id_distributor);
            }

            return $tpl->fetch('complaint_info.tpl', $complaint_id);
        } else {
            $this->conf['page_title'] = 'Поставщики по регионам. Адреса поставщиков, контракты и жалобы. Статистика выигранных тендеров и доходов от них.';
            $tpl = $this->new_tpl();
            $tpl->caching = true;
            $tpl->cache_lifetime = mt_rand(20, 45) * 59;

            if ($tpl->is_cached('distributor_list.tpl')) {
                return $tpl->fetch('distributor_list.tpl');
            } else {
                $x = $this->new_action('region_view');
                $tpl->assign('list', $x->run('distributor'));
                return $tpl->fetch('distributor_list.tpl');
            }
        }
    }

}